package com.app.business.web.business;

import com.app.business.en.FileStatus;
import com.app.business.model.Contract;
import com.app.business.model.FileInfo;
import com.app.business.service.ContractService;
import com.app.business.service.FileInfoService;
import com.app.business.utils.DownFilesZip;
import com.app.business.utils.Zip;
import com.app.system.config.properties.SystemParamProperties;
import com.app.system.jpa.PageBean;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.model.UserInfo;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.app.system.utils.upload.UploadInfo;
import com.app.system.utils.upload.UploadInfoUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 档案资料控制层
 *
 * @author lsh
 * @data 2019-5-30
 */
@Controller
@RequestMapping("/business/fileInfo/*")
public class FileInfoController {

    @Autowired
    private ContractService contractService;
    @Autowired
    private FileInfoService fileInfoService;
    @Autowired
    private DataDictService dataDictService;
    @Resource
    private SystemParamProperties systemParamProperties;

    @RequestMapping("commonListJson")
    @RequiresPermissions("fileInfo:commonListJson")
    @ResponseBody
    public Map commonListJson(HttpServletRequest request) {
        List<Map> listData = Lists.newArrayList();
        PageBean<Contract> contractPageBean = this.contractService.getContractPageBean();
        List<Contract> contractList = contractPageBean.getDatas();
        Map<String, DataDict> groupMap = this.dataDictService.getMapByParentNameForValue("组别");
        Map<Integer, Map> resultMap = this.fileInfoService.getFileNum("01");
        String allFileCount = "";

        if (CollectionUtils.isNotEmpty(contractList)) {
            Map<String, Object> item = null;
            for (Contract contract : contractList) {
                item = null;
                item = Maps.newHashMap();
                allFileCount = "";
                allFileCount = resultMap.get(contract.getId()) == null ? "" : resultMap.get(contract.getId()).get("allFileCount").toString();

                item.put("id", contract.getId());
                item.put("zsProjectName", StringUtils.getNotNull(contract.getZsProject().getProjectName()));
                item.put("groupCode", StringUtils.dataDictShow(groupMap.get(contract.getGroupCode())));
                item.put("contractCode", StringUtils.getNotNull(contract.getContractCode()));
                item.put("name", StringUtils.getNotNull(contract.getName()));
                item.put("allFileCount", allFileCount);
                listData.add(item);
            }
        }
        return LayUiUtils.page(contractPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 档案上传列表
     */
    @RequestMapping("list")
    @RequiresPermissions("fileInfo:list")
    public void list() {
    }


    /**
     * 主体方法
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("main")
    @RequiresPermissions("fileInfo:main")
    public void main(HttpServletRequest request, ModelMap modelMap) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkSqdsArguement(contract != null, "该数据不存在，请刷新重试！");
        modelMap.addAttribute("contract", contract);
        Map<String, List<String>> resultMap = Maps.newLinkedHashMap();

        List<DataDict> dataDictListCQ = dataDictService.findListByParentName("档案目录");
        List<String> cqList = Lists.newArrayList();

        List<String> allList = Lists.newArrayList();
        Map<String, String> fileInfoMap = dataDictService.getMapByParentNameForName_Value("档案类别");
        Map<String, List<String>> shMap = Maps.newHashMap();
        String fileCategory = null;
        //必须实例化
        for (DataDict dataDict : dataDictListCQ) {
            fileCategory = dataDict.getValue();
            cqList.add(fileCategory);
            allList.add(fileCategory);
        }

        resultMap.put(fileInfoMap.get("档案目录"), cqList);

        shMap = this.fileInfoService.getShNumber(contract.getId(), allList);
        //所有档案类别的一个Map，用于前台循环展示
        modelMap.addAttribute("resultMap", resultMap);
        modelMap.addAttribute("shMap", shMap);

        fileInfoMap = dataDictService.getMapByParentNameForValue_Name("档案类别");
        modelMap.addAttribute("fileInfoMap", fileInfoMap);

        Map<String, String> daMap = dataDictService.getMapByParentNameForValue_Name("档案目录");
        modelMap.addAttribute("daMap", daMap);

        //档案类别，本公司查看、上传本公司的档案,不传值查看所有
        modelMap.addAttribute("fileType", ParamUtils.getString(request, "fileType", ""));
    }

    /**
     * 对应某一目录的档案资料
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("right")
    @RequiresPermissions("fileInfo:right")
    public void right(HttpServletRequest request, ModelMap modelMap) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        String fileCategory = ParamUtils.getString(request, "fileCategory", "");
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkAjaxArguement(contract != null, "1111", "数据错误！");
        Map<String, String> fileMap = this.dataDictService.getMapByParentNameForName_Value("档案上传配置");
        //有效文件资料
        List<FileInfo> baseFileInfoList = this.fileInfoService.getFileInfoList(contract.getId(), fileCategory, FileStatus.YES.getIndex());
        modelMap.addAttribute("contract", contract);
        modelMap.addAttribute("fileCategory", fileCategory);
        modelMap.addAttribute("fileMap", fileMap);
        modelMap.addAttribute("baseFileInfoList", baseFileInfoList);
    }


    /**
     * 删除单个档案文件
     * zyk
     *
     * @param request
     * @return
     */
    @RequestMapping("deleteFileInfo")
    @ResponseBody
    @RequiresPermissions("fileInfo:deleteFileInfo")
    public synchronized Response deleteFileInfo(HttpServletRequest request) {
        Integer fileInfoId = ParamUtils.getInt(request, "fileInfoId", 0);
        FileInfo fileInfo = this.fileInfoService.findOne(fileInfoId);
        Precondition.checkAjaxArguement(fileInfo != null, "1111", "数据错误，删除失败！");
        fileInfo.setStatus(FileStatus.NO.getIndex());   //设置为无效状态
        this.fileInfoService.save(fileInfo);
        return new Response("0000", "操作成功");
    }


    /**
     * 文件上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "uploadSaveFile")
    @ResponseBody
    @RequiresPermissions("fileInfo:uploadSaveFile")
    public Map uploadSaveFile(HttpServletRequest request, HttpServletResponse response) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); // 定义路径,该路径便于文件拷贝
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssSSS"); // 定义文件名

        Integer contractId = ParamUtils.getInt(request, "contractId", 0);//家庭id
        String fileCategory = ParamUtils.getString(request, "fileCategory", "");//文件类别
        UserInfo user = WebUtils.getLoginUserInfo();

        String uploadPerson = user.getName();

        //缩略图宽高
        int width = ParamUtils.getInt(request, "width", 0);
        int height = ParamUtils.getInt(request, "height", 0);

        String path = systemParamProperties.getUploadFolder() + "file/" + sdf.format(new Date());// 路径
        String parameterName = sdf1.format(new Date());// 文件名称
        DecimalFormat decimalFormat = new DecimalFormat("0000");
        parameterName += decimalFormat.format((Math.random() * 10000));
        UploadInfo uploadInfo = UploadInfoUtil.uploadFile(request, path, "file", parameterName, true, width, height);


        String filePath = systemParamProperties.getStaticAccessPath() + "file/" + sdf.format(new Date()) + "/" + uploadInfo.getSaveFilename();// 上传文件路径
        String fileName = uploadInfo.getOriginalFilename();// 上传文件名称
        String suffixes = fileName.substring(fileName.lastIndexOf(".") + 1);

        fileName = fileName.substring(0, fileName.lastIndexOf("."));

        Long size = Long.valueOf(uploadInfo.getFileSize() + "");
        Map<String, String> map = Maps.newHashMap();
        try {
            FileInfo fileInfo = new FileInfo();
            Contract contract = contractService.findOne(contractId);
            Precondition.checkAjaxArguement(contract != null, "0012", "家庭不存在");
            fileInfo.setContract(contract);

            Date date = new Date();
            //正式
            fileInfo.setFileName(fileName);
            fileInfo.setFilePath(filePath);
            fileInfo.setSuffixes(suffixes);
            fileInfo.setFileSize(size);
            fileInfo.setUploadDate(date);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String numStr = format.format(date);
            fileInfo.setSortNum(99);
            fileInfo.setSort(Long.valueOf(numStr));
            fileInfo.setUploadPerson(uploadPerson);
            fileInfo.setFileCategory(fileCategory);
            fileInfo.setFileType(fileCategory.substring(0, 2));
            this.fileInfoService.save(fileInfo);

            map.put("success", "true");
            map.put("dataOriginal", "/" + fileInfo.getFilePath());
            map.put("fileInfoId", fileInfo.getId().toString());
            map.put("src", fileInfo.getSmallPic());
        } catch (Exception e) {//保存信息失败，并删除已经上传的文件
            map.put("success", "false");
            map.put("dataOriginal", "");
            map.put("fileInfoId", "");
            map.put("src", "");
        }
        return map;
    }


    /**
     * 得到个文件类型档案数量的map
     * 2017/06/27
     * zyk
     *
     * @param request
     */
    @RequestMapping("shMap")
    @ResponseBody
    @RequiresPermissions("fileInfo:shMap")
    public Map shMap(HttpServletRequest request) {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);
        String fileCategory = ParamUtils.getString(request, "fileCategory", "");
        Contract contract = this.contractService.findOne(contractId);
        //shMap
        int number = this.fileInfoService.getShNumber(contract.getId(), fileCategory);
        Map<String, Integer> resultMap = Maps.newHashMap();
        resultMap.put("result", number);
        return resultMap;
    }

    /**
     * 档案资料信息修改
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("fileInfoForm")
    @RequiresPermissions("fileInfo:fileInfoForm")
    public void fileInfoForm(HttpServletRequest request, ModelMap modelMap) {
        Integer fileInfoId = ParamUtils.getInt(request, "fileInfoId", 0);
        FileInfo fileInfo = this.fileInfoService.findOne(fileInfoId);
        Precondition.checkSqdsArguement(fileInfo != null, "数据错误！");
        modelMap.addAttribute("fileInfo", fileInfo);
    }

    /**
     * 档案保存
     *
     * @param request
     * @return
     */
    @RequestMapping("fileInfoSave")
    @ResponseBody
    @RequiresPermissions("fileInfo:fileInfoSave")
    public synchronized Response fileInfoSave(HttpServletRequest request) {
        Integer fileInfoId = ParamUtils.getInt(request, "fileInfoId", 0);
        FileInfo fileInfo = this.fileInfoService.findOne(fileInfoId);
        Precondition.checkSqdsArguement(fileInfo != null, "数据错误！");
        WebUtils.bind(request, fileInfo);
        this.fileInfoService.save(fileInfo);
        return new Response("0000", "操作成功");
    }


    /**
     * 批量下载某一目录的文件
     *
     * @param request
     */
    @RequestMapping("batchDownFile")
    @RequiresPermissions("fileInfo:batchDownFile")
    public void batchDownFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer contractId = ParamUtils.getInt(request, "contractId", 0);//家庭id
        String fileCategory = ParamUtils.getString(request, "fileCategory", "");//档案目录
        Contract contract = this.contractService.findOne(contractId);
        Precondition.checkSqdsArguement(contract != null && !fileCategory.equals(""), "数据错误！");
        List<FileInfo> list = this.fileInfoService.getFileInfoList(contract.getId(), fileCategory, FileStatus.YES.getIndex());

        Precondition.checkSqdsArguement(CollectionUtils.isNotEmpty(list), "找不到下载的文件！");

        List<DataDict> dataDictListCQ = dataDictService.findListByParentName("档案目录");
        Map<String, String> folderMap = Maps.newHashMap();
        for (DataDict dataDict : dataDictListCQ) {
            folderMap.put(dataDict.getValue(), dataDict.getName());
        }

        List<Zip> fileList = Lists.newArrayList();
        for (FileInfo f : list) {
            String path = f.getFilePath().replace("/upload", "");
            path = systemParamProperties.getUploadFolder() + path;
            path = path.replace("/", "\\");

            Zip zip = new Zip();
            zip.setFilePath(path);
            zip.setFolderName(Strings.nullToEmpty(folderMap.get(f.getFileType())));
            fileList.add(zip);
        }
        // 生成的ZIP文件名
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ssSSS");
        String zipName = folderMap.get(fileCategory) == null ? "" : folderMap.get(fileCategory);
        String strName = zipName + format.format(new Date()) + ".zip";
        String strZipName = systemParamProperties.getUploadFolder() + "/" + strName;
        try {
            DownFilesZip.downLoadZipFiles(strZipName, fileList, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
